package com.aytbayev.asyl;

import java.util.Collections;
import java.util.LinkedList;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

public class StocksGrid extends Activity{
	
	private static final String USER_DETAILS = "UserPrefs";

	private ProgressDialog instr_ProgressDialog = null;
	private LinkedList<Instrument> instruments = null;
	private InstrumentAdapter instr_adapter;
	private Runnable viewStocks;
	private volatile Thread getInstrumentsThread;
	private volatile boolean stopStocksUpdate = false;
	private SharedPreferences settings;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.stocks_grid);
		
		Log.d("TAG", "StocksGrid onCreate()");

		this.instruments = new LinkedList<Instrument>();
		
		GridView gridview = (GridView) findViewById(R.id.stocks_gridview);
		instr_adapter = new InstrumentAdapter(this, instruments);
	    gridview.setAdapter(instr_adapter);
	    
	    gridview.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				Instrument o = instruments.get(position);
				Bundle bundle = new Bundle();
				bundle.putString("idKase", Integer.toString(o.getIdKase()));
				bundle.putString("typeGlass", Byte.toString(o.getTypeGlass()));
				bundle.putString("shortName", o.getShortName());
				Intent myIntent = new Intent(StocksGrid.this, Stakan.class);
				myIntent.putExtras(bundle);
				StocksGrid.this.startActivity(myIntent);
			}
		});
				
		viewStocks = new Runnable() {
			//@Override
			public void run() {
				while (true) {
					try {
						if (!stopStocksUpdate) {
							getInstruments();
							Log.d("Blink", "--------------------------------------");
						}	
						Thread.sleep(10000);
					} catch (InterruptedException e) {
						Log.e("BACKGROUND_PROC", e.getMessage());
					}
				}

			}
		};
		
		if (getInstrumentsThread == null) {
			getInstrumentsThread = new Thread(null, viewStocks, "MagentoBackground");
			getInstrumentsThread.start();
		}
		instr_ProgressDialog = ProgressDialog.show(StocksGrid.this,
				this.getString(R.string.wait),
				this.getString(R.string.loading), true);
	}
		
	@Override
	public void onResume() {
		super.onResume();
		stopStocksUpdate = false;
	}

	@Override
	public void onPause() {
		super.onPause();
		stopStocksUpdate = true;
	}

	private Runnable returnRes = new Runnable() {
		// @Override
		public void run() {
			if (instruments != null && instruments.size() > 0) {
				instr_adapter.notifyDataSetChanged();				
			}
			instr_ProgressDialog.dismiss();
			// instr_adapter.notifyDataSetChanged();
		}
	};

	private void getInstruments() {
		settings = getSharedPreferences(USER_DETAILS, Context.MODE_PRIVATE);
		String clientId = settings.getString("clientId", "0");
		DataManager.fillInstrumentsMobile(instruments, clientId);
		Collections.sort(instruments, new InstrumentComparator());
		runOnUiThread(returnRes);
	}
		
	private static class ViewHolder {
		public ImageView image;
		public TextView ticker;
		public TextView status;
		public TextView last;
		public TextView bid;
		public TextView ask;
		public TextView daily;
		public boolean isBlinking;
	}

	private class InstrumentAdapter extends BaseAdapter {
		private Activity activity;
		private LinkedList<Instrument> items;
		private LayoutInflater inflater = null;
	    
	    public InstrumentAdapter(Activity activity, LinkedList<Instrument> items) {
	    	this.activity = activity;
			this.items = items;
			inflater = LayoutInflater.from(activity);
		}
	    
	    public Object getItem(int position) {
	        return null;
	    }

	    public long getItemId(int position) {
	        return position;
	    }
	    
	    public View getView(int position, View convertView, ViewGroup parent) {
	    	View vi = convertView;
	        ViewHolder holder;    	        	
            
	        if(vi == null){
	            vi = inflater.inflate(R.layout.stocks_grid_item, null);          
	            
	            holder = new ViewHolder();
	            holder.image = (ImageView)vi.findViewById(R.id.background_img);
	            holder.ticker = (TextView)vi.findViewById(R.id.ticker_t);
	            holder.status = (TextView)vi.findViewById(R.id.status);
	            holder.last = (TextView)vi.findViewById(R.id.last);
	            holder.ask = (TextView)vi.findViewById(R.id.ask);
	            holder.bid = (TextView)vi.findViewById(R.id.bid);	            
	            holder.daily = (TextView)vi.findViewById(R.id.daily);
	            
	            vi.setTag(holder);
	        } else {
	        	 holder = (ViewHolder) convertView.getTag();
	        }             
	        
	        Instrument o = items.get(position);
	        if (o != null) {
	        	Resources res = getResources();
	        	
	        	//holder.image.setAlpha(200);        	
		        holder.ticker.setText(o.getShortName());
		        holder.status.setText(o.getStatus());		        
		        holder.last.setText(o.format(o.getLast()));
		        holder.ask.setText(o.format(o.getAsk()));  
		        holder.bid.setText(o.format(o.getBid()));
		        holder.daily.setText(o.format(o.getPctChg1d()) + "%");	        
		        
		        // if Frankfurt, color all in turquoise 
				if (o.getStatus().equals("F")) {
		        	Log.d("TAG", "Frankruft " + o.getShortName());
		        	holder.ticker.setTextColor(res.getColor(R.color.turquoise));
		        	holder.status.setTextColor(res.getColor(R.color.turquoise));
		        	holder.last.setTextColor(res.getColor(R.color.turquoise));
		        	holder.ask.setTextColor(res.getColor(R.color.turquoise));
		        	holder.bid.setTextColor(res.getColor(R.color.turquoise));
	        	} else {	        		
	        		holder.ticker.setTextColor(res.getColor(R.color.black));
		        	holder.status.setTextColor(res.getColor(R.color.black));
		        	holder.last.setTextColor(res.getColor(R.color.black));
		        
			        // color plashka according to last
			        if (o.getLast() != 0) {
			        	if (o.getLast() > o.getLastH() && !holder.isBlinking) {
			        		holder.image.setImageResource(R.drawable.rect_green_3);
			        		
			        	} else if (o.getLast() < o.getLastH()) {
			        	//} else if (o.getBlink() && !holder.isBlinking) {
			        		holder.image.setImageResource(R.drawable.rect_red_3);
			        		
//			        		holder.image.setBackgroundResource(R.drawable.blink_red);
//			        		AnimationDrawable rectAnimation = (AnimationDrawable) holder.image.getBackground();
//			        		rectAnimation.start();
//			        		holder.isBlinking = true;
			        	} else {
//			        		if (holder.isBlinking) {
//			        			((AnimationDrawable) holder.image.getBackground()).stop();
//			        		}
			        		holder.image.setImageResource(R.drawable.rect_gray_3);   
			        		//holder.isBlinking = false;
			        	}
			        } else {
			        	holder.image.setImageResource(R.drawable.rect_gray_3);
			        }
			        		             
			        // color bid and ask	                
					if (o.getAsk() != 0 && o.getBid() != 0) {
						if (o.getAsk() > o.getAskH()) {
							holder.ask.setTextColor(res.getColor(R.color.green));
							holder.ask.setTypeface(null, 1); //bold
						} else if (o.getAsk() < o.getAskH()) {
							holder.ask.setTextColor(res.getColor(R.color.red));
							holder.ask.setTypeface(null, 1);
						} else {
							holder.ask.setTextColor(res.getColor(R.color.black));
							holder.ask.setTypeface(null, 0);
						}
						
						if (o.getBid() > o.getBidH()) {
							holder.bid.setTextColor(res.getColor(R.color.green));
							holder.bid.setTypeface(null, 1);
						} else if (o.getBid() < o.getBidH()) {
							holder.bid.setTextColor(res.getColor(R.color.red));
							holder.bid.setTypeface(null, 1);
						} else {
							holder.bid.setTextColor(res.getColor(R.color.black));
							holder.bid.setTypeface(null, 0);
						}
					} else {
						holder.ask.setTextColor(res.getColor(R.color.black));
						holder.bid.setTextColor(res.getColor(R.color.black));
						holder.ask.setTypeface(null, 0);
						holder.bid.setTypeface(null, 0);
					}
					
	        	}				
		        
		        if (o.getPctChg1d() > 0) {
		        	holder.daily.setTextColor(res.getColor(R.color.dark_green));
		        } else if (o.getPctChg1d() < 0) {
		        	holder.daily.setTextColor(res.getColor(R.color.red));
		        } else {
		        	holder.daily.setText("0%");
		        	holder.daily.setTextColor(res.getColor(R.color.black));
		        }
		        
		        
	        }
	        return vi;

	    }

		@Override
		public int getCount() {
			return items.size();
		}
	}
}